package com.mbsnjdxyry.tracord_backend.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mbsnjdxyry.tracord_backend.common.ResponseResult;
import com.mbsnjdxyry.tracord_backend.common.ResultCode;
import com.mbsnjdxyry.tracord_backend.domain.PassageFollowerNum;
import com.mbsnjdxyry.tracord_backend.domain.PassageInfo;
import com.mbsnjdxyry.tracord_backend.domain.dto.ArgumentDto;
import com.mbsnjdxyry.tracord_backend.domain.vo.PassageToFront;
import com.mbsnjdxyry.tracord_backend.mapper.PassageFollowerNumMapper;
import com.mbsnjdxyry.tracord_backend.mapper.PassageInfoMapper;
import com.mbsnjdxyry.tracord_backend.mapper.UserMapper;
import com.mbsnjdxyry.tracord_backend.service.AsyncService;
import com.mbsnjdxyry.tracord_backend.service.UserService;
import com.mbsnjdxyry.tracord_backend.utils.PassageToFrontConverter;
import com.mbsnjdxyry.tracord_backend.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private UserService userService;

    @Autowired
    private PassageFollowerNumMapper passageFollowerNumMapper;

    @Autowired
    private PassageInfoMapper passageInfoMapper;

    @Autowired
    private PassageToFrontConverter passageToFrontConverter;

    //用于存储异步请求的结果
    private List<String> res;

    @Override
    public void setAsyncRes() {
        WebClient webClient = WebClient.create();

        // 请求URL和参数
        String url = "http://124.221.252.192:5000/images";
        //参数
        ArgumentDto argumentDto = new ArgumentDto();
        this.setUserNum(argumentDto);
        this.setUserId(argumentDto);
        this.setLike(argumentDto);
        this.setUrlList(argumentDto);
        System.out.println(JSON.toJSONString(argumentDto));

        webClient.post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(argumentDto))
                .retrieve()
                .bodyToMono(List.class)
                .subscribe(response -> {
                    // 请求成功时的处理逻辑
                    res = response;
                    System.out.println("异步POST请求成功，结果为：" + res);
                }, error -> {
                    // 请求失败时的处理逻辑
                    System.out.println("异步POST请求失败，原因为：" + error.getMessage() + "\n" + error.getCause() + "\n" + error.getLocalizedMessage());
                });

        //return ResponseResult.success(ResultCode.ASYNC_SUCCESS,res);
    }

    @Override
    public ResponseResult getAsyncRes() {
        //根据返回的 url 查询对应的帖子并返回给前端
        List<PassageInfo> passageInfoList = new ArrayList<>();
        if(res == null){
            //算法还在计算中, res 还没被赋值
            return ResponseResult.error(ResultCode.ASYNC_IS_RUNNING,null);
        }else{
            //算法计算出结果了
            for (String r : res) {
                LambdaQueryWrapper<PassageInfo> lqw = new LambdaQueryWrapper<>();
                //找到图片 url 与返回的 url 相同的帖子, 排除当前用户自己的帖子
                lqw.eq(PassageInfo::getImage,r).ne(PassageInfo::getUserId,SecurityUtils.getUserId());
                PassageInfo passageInfo = passageInfoMapper.selectOne(lqw);
                if(passageInfo != null){
                    passageInfoList.add(passageInfo);
                }
            }

            //得出的 passageInfoList 转化为展示给前端的数据
            List<PassageToFront> passageToFrontList = passageToFrontConverter.getPassageToFrontList(passageInfoList);

            return ResponseResult.success(ResultCode.ASYNC_SUCCESS,passageToFrontList);
        }

    }

    private void setUserNum(ArgumentDto argumentDto){
        //获取 user_num
        int user_num = userService.count();
        argumentDto.setUser_num(String.valueOf(user_num));
        //return argumentDto;
    }

    private void setUserId(ArgumentDto argumentDto){
        //获取 user_id
        if(SecurityUtils.getAuthentication() != null
                && SecurityUtils.getLoginUser() != null ){
            argumentDto.setUser_id(String.valueOf(SecurityUtils.getUserId()));
        }else{
            argumentDto.setUser_id("2");
        }
    }

    private void setLike(ArgumentDto argumentDto){
        //获取 like 二维数组
        List<List<String>> like = new ArrayList<>();
        List<PassageFollowerNum> passageFollowerNums = passageFollowerNumMapper.selectList(null);

        //输出数据测试
        System.out.println(passageFollowerNums);

        for (PassageFollowerNum passageFollowerNum : passageFollowerNums) {
            List<String> item = new ArrayList<>();
            item.add(passageFollowerNum.getFollowerId().toString());
            //查询该帖子的图片的 url
            LambdaQueryWrapper<PassageInfo> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PassageInfo::getId,passageFollowerNum.getPassageId());
            PassageInfo passageInfo = passageInfoMapper.selectOne(lqw);
            item.add(passageInfo.getImage());
            like.add(item);
        }

        argumentDto.setLike(like);
    }

    private void setUrlList(ArgumentDto argumentDto){
        List<PassageInfo> passageInfos = passageInfoMapper.selectList(null);
        List<String> urlList = new ArrayList<>();
        for (PassageInfo passageInfo : passageInfos) {
            urlList.add(passageInfo.getImage());
        }

        argumentDto.setUrl_list(urlList);
    }
}
